package conf

import (
	"bufio"
	"easy-proxy/node"
	"io"
	"os"
	"strconv"
	"strings"
)

const middle = "="

type Config struct {
	MyConf map[string]string
	strcet string
}

func (c *Config) InitConfig(path string) {
	c.MyConf = make(map[string]string)

	f, err := os.Open(path)
	if err != nil {
		panic(err)
	}
	defer f.Close()

	r := bufio.NewReader(f)
	for {
		b, _, err := r.ReadLine()
		if err != nil {
			if err == io.EOF {
				break
			}
			panic(err)
		}

		s := strings.TrimSpace(string(b))
		//fmt.Println(s)
		if strings.Index(s, "#") == 0 {
			continue
		}

		n1 := strings.Index(s, "[")
		n2 := strings.LastIndex(s, "]")
		if n1 > -1 && n2 > -1 && n2 > n1+1 {
			c.strcet = strings.TrimSpace(s[n1+1 : n2])
			continue
		}

		if len(c.strcet) == 0 {
			continue
		}
		index := strings.Index(s, "=")
		if index < 0 {
			continue
		}

		frist := strings.TrimSpace(s[:index])
		if len(frist) == 0 {
			continue
		}
		second := strings.TrimSpace(s[index+1:])

		pos := strings.Index(second, "\t#")
		if pos > -1 {
			second = second[0:pos]
		}

		pos = strings.Index(second, " #")
		if pos > -1 {
			second = second[0:pos]
		}

		pos = strings.Index(second, "\t//")
		if pos > -1 {
			second = second[0:pos]
		}

		pos = strings.Index(second, " //")
		if pos > -1 {
			second = second[0:pos]
		}

		if len(second) == 0 {
			continue
		}

		key := c.strcet + middle + frist
		c.MyConf[key] = strings.TrimSpace(second)
	}
}

/**
读取默认配置
*/
func (c Config) Read(node, key string) string {
	key = node + middle + key
	v, found := c.MyConf[key]
	if !found {
		return ""
	}
	return v
}

/**
读取节点配置
*/
func (c Config) ReadNode() []*node.Node {
	var l []*node.Node
	nodeNme := make(map[string]string)
	for k := range c.MyConf {
		key := string([]rune(k)[:5])
		if string([]rune(k)[:4]) == "node" {
			if _, ok := nodeNme[key]; !ok {
				nodeNme[key] = key
			}
		}
	}
	for k := range nodeNme {
		n := &node.Node{}
		n.Ip = c.Read(k, "ip")
		n.Hostname = c.Read(k, "hostname")
		i, err := strconv.Atoi(c.Read(k, "port"))
		if err == nil {
			n.Port = i
		}
		n.Port = i
		j, err := strconv.Atoi(c.Read(k, "weight"))
		if err == nil {
			n.Weight = j
			n.EffectWeight = j
		}
		l = append(l, n)
	}
	return l
}
